//
//  HSLoginController.swift
//  Home_School_08
//
//  Created by 张晓林 on 2016/12/22.
//  Copyright © 2016年 张晓林. All rights reserved.
//

import UIKit
import SVProgressHUD

class HSLoginController: UIViewController {

    @IBOutlet weak var accountT: UITextField!
    @IBOutlet weak var passwordT: UITextField!
    @IBOutlet weak var loginBtn: UIButton!
    // 创建一个全局的活动指示器
    let activity = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.white)
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        setupUI()
    }
    
    func setupUI() {
        // 设置输入框左边视图
        accountT.leftView = setLeftV(imageName: "icon_user")
        accountT.leftViewMode = .always
        // 密码
        passwordT.leftView = setLeftV(imageName: "icon_password")
        passwordT.leftViewMode = .always
        
        // 设置登录按钮的圆角和边框
        loginBtn.layer.cornerRadius = 5
        loginBtn.layer.masksToBounds = true
        // 设置边框
        loginBtn.layer.borderWidth = 2
        let col = UIColor(red: 54/255.0, green: 147/255.0, blue: 1.0, alpha: 1.0)
        loginBtn.layer.borderColor = col.cgColor
    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        // 添加活动指示器
        activity.center = CGPoint(x: screenW/2, y: passwordT.frame.maxY + 15)
        view.addSubview(activity)
    }
    
    // 左边视图
    func setLeftV(imageName: String) -> UIView {
        // 创建一个背景视图
        let bgView = UIView(frame: CGRect(x: 0, y: 0, width: 44, height: 44))
        // 获得图片
        let img = UIImage(named: imageName)
        // 创建第一张图片视图
        let firstV = UIImageView(image: img)
        firstV.center = CGPoint(x: (img?.size.width)!/2 + 8, y: 22)
        bgView.addSubview(firstV)
        // 第二张图片
        let secondV = UIImageView(image: UIImage(named: "line_edit_sep"))
        secondV.center = CGPoint(x: firstV.frame.maxX + 10, y: 22)
        bgView.addSubview(secondV)
        return bgView
    }
    
    @IBAction func loginBtnClicked() {
        // 先判断学校IP是否设置
        guard baseURLStr == nil || baseURLStr == "http://120.24.57.38/new/" else {
            SVProgressHUD.showProgress(0.2, status: "请正确输入你的学习IP地址")
            SVProgressHUD.dismiss(withDelay: 1)
            return
        }
        guard accountT.text != "" else {
            HSAlertView.bottomAlertView("账号不能为空")
            return
        }
        guard passwordT.text != "" else {
            HSAlertView.bottomAlertView("密码不能为空")
            return
        }
        // 开始加载网络，显示菊花
        activity.startAnimating()
        // 获得网络接口
        let urlStr = "ZH-schoolname-S-login"
        // 设置参数
        let parm = ["code": accountT.text!,"password":passwordT.text!]
        // 调用网络单利方法请求数据
        HSNetworkTools.shared.request(url: urlStr, parameters: parm) {[weak self] (data, err) in
            // 关闭活动指示器
            self?.activity.stopAnimating()
            // 判断并处理数据是否为空
            guard let data = data as? NSDictionary else {
                HSAlertView.bottomAlertView("登录失败，请检查你的网络")
                return
            }

            // 判断账号密码错误
            let result = data["result"] as! Int
            switch result {
            case 0:
                print("设置登录")
                // 获得用户信息字典
                let userInfo = data["data"] as! NSDictionary
                // 保存数据
                UserDefaults.standard.set(userInfo, forKey: UserInfoSaveK)
                // 设置页面跳转
                UIApplication.shared.keyWindow?.rootViewController = HSDrawerController()
                // 保存登录状态
                UserDefaults.standard.set(true, forKey: isLoginKey)
            case 1:
                print("提示错误")
            default:
                break
            }
        }
    }
    
    @IBAction func settingBtnClicked() {
        // 创建弹窗
        let alertVc = UIAlertController(title: "请输入学校的IP地址:", message: nil, preferredStyle: .alert)
        
        alertVc.addTextField { (textF) in
            textF.placeholder = "学校IP地址"
            //textF.borderStyle = .roundedRect
            // 获得已经保存的地址
            let IPStr = UserDefaults.standard.object(forKey: IPSaveKey)
            textF.text = IPStr as? String
        }
        // 添加确定按钮
        alertVc.addAction(UIAlertAction(title: "确定", style: .default) { (_) in
            // 获得当前输入框的内容
            let inputIP = alertVc.textFields?[0].text
            // 记录保存当前输入内容
            UserDefaults.standard.set(inputIP, forKey: IPSaveKey)
        })
        // 添加取消按钮
        alertVc.addAction(UIAlertAction(title: "取消", style: .cancel, handler: nil))
        // 显示弹窗
        present(alertVc, animated: true, completion: nil)
    }
    
    // 退出键盘
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        view.endEditing(true)
    }
    
    deinit {
        print("HSLoginController消失了")
    }
}






